import sublime,sublime_plugin
import os,re


EXT_JS = ['.js','.ts','.vue', '.cjs', '.mjs']
EXT_PY = ['.py','.pyc']

PRINT_COMMAND = {
    "python":{
        "ext":['.py','.pyc'],
        "command":'{indent}print("{param}: ", {param})\n',
    },
    "javascript":{
        "ext":['.js','.ts','.vue', '.cjs', '.mjs'],
        "command":'{indent}console.log("{param}: ", {param})\n'
    }
}

PACKAGE_NAME = 'cps-plugin'

if int(sublime.version()) < 3176:
    raise ImportWarning("本插件不支持当前版本，请使用大于等于3176的sublime Text")

def plugin_loaded():
    print('loaded {} plugin'.format(PACKAGE_NAME))
    PLUGIN_SETTINGS = {}


class CpsPrintParamCommand(sublime_plugin.TextCommand):
    """
    @Description 快速打印一个参数
    """
    def run(self, edit):
        view = self.view
        global PRINT_COMMAND

        # 获取当前行的region
        currt_region:sublime.Region =  self.view.sel()[0]
        currt_line_region = view.full_line(currt_region)

        # 获取下一行
        newt_line_start:int = currt_line_region.b

        # 获取关键字
        select_str = self.view.substr(currt_region)
        if not select_str or len(select_str) <= 0:
            return print('没有任何选择')

        # 获取前置缩进
        currt_line_str = self.view.substr(currt_line_region)

        # 提取前缩进
        res = re.compile(r'^(\s*)?(.*)').findall(currt_line_str)

        # 根据不同格式插入不同
        name,ext = os.path.splitext(view.file_name())

        for key,val in PRINT_COMMAND.items():
            if ext in PRINT_COMMAND[key]['ext']:
                command = PRINT_COMMAND[key]['command'].format(indent=res[0][0], param=select_str)
                view.insert(edit, newt_line_start, command)
                return
                break

        return print('not suport ext: ', ext)

# 打开当前文件的文件夹
class CpsOpenCurrtFolderCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        #调用当前激活的窗口来执行 run_command 命令(无法使用 self.view 调用 run_command)
        fdir, fname = os.path.split(self.view.file_name()) 
        sublime.active_window().run_command("open_dir", {"dir": fdir})

# 设置语法
class CpsSetSyntaxCommand(sublime_plugin.TextCommand):
    def run(self,edit,syntax):
        syntaxDict = {
          "html":"Packages/HTML/HTML.sublime-syntax",
          "vue":"Packages/Vue Syntax Highlight/Vue Component.sublime-syntax",
          "js":"Packages/JavaScriptNext - ES6 Syntax/JavaScriptNext.tmLanguage"
        }
        if syntax : self.view.set_syntax_file(syntaxDict[syntax])

# 清除所有注释
class CpsRemoveCommentsCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        comments = self.view.find_by_selector('comment')
        # 遍历所有注释块
        for region in reversed(comments):
            self.view.erase(edit, region)
